package com.kuqi.crs.util;

import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author:kuqi
 * @createTime:2021/9/23 10:45
 * @description:事务的动态代理
 */
public class TransactionInvocationHandler implements InvocationHandler {
    private Object target;//需要代理的目标类

    public TransactionInvocationHandler(Object target) {
        this.target = target;
    }

    //需要代理目标的方法，即业务逻辑层的方法
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object object = null;
        SqlSession sqlSession = null;
        try {
            sqlSession = SqlSessionUtil.getSqlSession();
            object = method.invoke(target, args); //执行方法返回的数据
            sqlSession.commit();//提交到数据库
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw e.getCause();//将错误继续往上抛
        } finally {
            SqlSessionUtil.myClose(sqlSession);//关闭资源
        }
        return object;
    }

    //获取代理类对象
    public Object getProxy(){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
    }
}
